package com.lunker.moneyrecord;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

public class ExportDatabaseTask extends AsyncTask<Void, Void, Boolean> {
	
	private Context context = null;
	private BetterProgressDialog progressDlg = null;
	private static final String BACKUP_FILE_NAME = "MoneyRecord.db";
	
	public ExportDatabaseTask (Context c) {
		context = c;
	}
	
	@Override
	protected void onPreExecute() {
		progressDlg = new BetterProgressDialog(context);
		progressDlg.show();
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return false;
		}
		
		File fdb = new File(Environment.getDataDirectory(), 
				"data/" + context.getPackageName() + "/databases/account_book");
		File fbak = new File(Environment.getExternalStorageDirectory(), BACKUP_FILE_NAME);
		FileChannel fcin = null;
		FileChannel fcout = null;
		
		try {
			fbak.createNewFile();
			fcin = new FileInputStream(fdb).getChannel();
			fcout = new FileOutputStream(fbak).getChannel();
			fcin.transferTo(0, fcin.size(), fcout);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (fcin != null) {
					fcin.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
			
			try {
				if (fcout != null) {
					fcout.close();
				}
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}		
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		progressDlg.dismiss();
		
		if (result) {
			Toast.makeText(context, context.getString(R.string.export_db_successfully), 
					Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(context, context.getString(R.string.fail_to_export_db), 
					Toast.LENGTH_SHORT).show();
		}
	}
}
